package com.wangyi.basic.controller;

import com.wangyi.basic.util.AjaxResult;
import com.wangyi.basic.util.FastDfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 上传：1 - Post
 * 下载：不需要
 * 删除：1 - Delete
 * 修改： = 删除 + 上传
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    /**
     * 上传接口
     * @param file
     * @return
     */
    @PostMapping
    public AjaxResult upload(@RequestPart(required = true,value = "file") MultipartFile file){

        try {
            System.out.println(file.getOriginalFilename() + ":" + file.getSize());
            // 获取原始名字
            String originalFilename = file.getOriginalFilename();
            // xxx.jpg,获取后缀
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
            // 调用工具类,返回上传后的路径
            String filePath =  FastDfsUtil.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(filePath); //把上传后的路径返回回去
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("上传失败!"+e.getMessage());
        }
    }

    /**
     * 删除接口
     * @param path
     * @return
     */
    @DeleteMapping
    public AjaxResult del(@RequestParam(required = true,value = "path") String path){
        try {
            String pathTmp = path.substring(1); // goup1/xxxxx/yyyy
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);// /xxxxx/yyyy
            System.out.println(groupName);
            System.out.println(remotePath);
            FastDfsUtil.delete(groupName, remotePath);
            return  AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除失败!"+e.getMessage());
        }
    }

}

